/*
 * Copyright (c) 2011, Janni Kovacs
 * All rights reserved.
 *
 * Redistribution and use of this software in source and binary forms, with or without modification, are
 * permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above
 *   copyright notice, this list of conditions and the
 *   following disclaimer in the documentation and/or other
 *   materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package de.umass.lastfm2itunes.core;

import java.util.List;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ITunesConnector {

	private ScriptEngine engine;

	public ITunesConnector() {
		ScriptEngineManager sem = new ScriptEngineManager();
		this.engine = sem.getEngineByName("AppleScriptEngine");
		// this.engine = sem.getEngineByName("Java-AppleScript-Connector");
	}

	public void addPlayCount(String trackSearchQuery, int playCount) throws ScriptException {
		/*
		 * String script = "tell application \"iTunes\"\n"+
		 * "set sresult to (search library playlist 1 for \""
		 * +trackSearchQuery+"\")\n"+ "repeat with aTrack in sresult\n"+
		 * "if class of aTrack is file track then\n"+
		 * "set played count of aTrack to "
		 * +playCount+" + (get played count of aTrack)\n"+ "exit repeat\n"+
		 * "end if\n"+ "end repeat\n"+ "end tell";
		 */
		String script = "tell application \"iTunes\"\n" + "set aTrack to item 1 of (search library playlist 1 for \""
				+ trackSearchQuery + "\")\n" + "set played count of aTrack to " + playCount
				+ " + (get played count of aTrack)\n" + "end tell";
		engine.eval(script);
	}

	public void setPlayCount(String trackSearchQuery, int playCount) throws ScriptException {
		String script = "tell application \"iTunes\"\n"
				+ "set played count of item 1 of (search library playlist 1 for \"" + trackSearchQuery + "\") to "
				+ playCount + "\n" + "end tell";
		engine.eval(script);
	}

	public void resetAllPlayCounts() throws ScriptException {
		engine.eval("tell application \"iTunes\"\n"
				+ "set played count of every file track of library playlist 1 to 0\n" + "end tell");
	}

	public void setPlayCounts(List<ITrack> queries) {
		StringBuilder b = new StringBuilder(50 + queries.size() * 200);
		b.append("tell application \"iTunes\"\n");
		for (ITrack iTrack : queries) {
			b.append("set sr to (every file track of library playlist 1 whose artist equals \"");
			 b.append(iTrack.artist.replace("\"", "\\\""));
		//	b.append("hans");
			b.append("\" and name equals \"");
			 b.append(iTrack.name.replace("\"", "\\\""));
		//	b.append("peter");
			b.append("\")\n");
			 b.append("if (count of sr) > 0 then\n");
			 b.append("set played count of item 1 of sr to ");
			 b.append(iTrack.playCount);
			 b.append("\n");
			 b.append("end if\n");
		}
		b.append("end tell");
		// System.out.println("\n\n========"+b+"\n\n========");
		try {
			engine.eval(b.toString());
		} catch (ScriptException e) {
			e.printStackTrace();
			System.out.println("=============");
			System.out.println(e.getMessage() + " at line " + e.getLineNumber() + " column " + e.getColumnNumber());
			System.out.println(b);
			System.out.println("=============");
		}
	}

	public static void main(String[] args) {
		ScriptEngineManager sem = new ScriptEngineManager();
		ScriptEngine engine = sem.getEngineByName("AppleScriptEngine");
		System.out.println(engine.getFactory().getEngineName());
		System.out.println(engine.getFactory().getEngineVersion());
		System.out.println(engine.getFactory().getLanguageName());
		System.out.println(engine.getFactory().getLanguageVersion());
		StringBuilder b = new StringBuilder(50);
		b.append("tell application \"iTunes\"\n");
//		b.append("set asdasdasd to (every file track of library playlist 1 whose artist contains \"hans\")\n");
		b.append("(every file track of library playlist 1 whose artist equals \"depeche mode\")\n");
		// b.append("if (count of sr) > 0 then\n");
		// b.append("set played count of item 1 of sr to ");
		// b.append(iTrack.playCount);
		// b.append("\n");
		// b.append("end if\n");
		b.append("end tell");
		// System.out.println("\n\n========"+b+"\n\n========");
		try {
			engine.eval(b.toString());
		} catch (ScriptException e) {
			e.printStackTrace();
			System.out.println("=============");
			System.out.println(e.getMessage() + " at line " + e.getLineNumber() + " column " + e.getColumnNumber());
			System.out.println(b);
			System.out.println("=============");
		}
	}
}
